#!/usr/bin/env node

const http = require('http'),
      fs = require('fs'),
      url = require('url'),
      log  = console.log;
let html = fs.readFileSync('./index.html').toString('utf8');

let dataList = require('./data.js');
dataList = dataList.filter((item)=>{
  return item.movieRange != '暂无评分';
});

dataList = dataList.sort(compare('movieRange',false));
dataList = dataList.reverse();
log(dataList);

function compare(property){
  return function(a,b){
    let value1 = a[property];
    let value2 = b[property];
    return value1-value2;
  };
}

http.createServer((req,res)=>{
  let addr = url.parse(req.url);
  if(addr.pathname == '/'){
    res.writeHead(200,{
      'Content-Type':'text/html',
      'Content-Length':Buffer.byteLength(html)
    });

    res.end(html);

  }else if(addr.pathname == '/getlist'){
    res.writeHead(200,{
      'content-type':'application/json'
    });
    res.end(JSON.stringify(dataList));
  }
  else{
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found!</h1>');
    return;
  }
}).listen(8080);
